package yja.gzw.app.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import cn.jzvd.Jzvd
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import yja.gzw.app.R
import yja.gzw.app.adapter.FabuAdapter
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityShipingjianjiBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import java.io.File

class ShipingjianjiActivity :BaseActivity<Mainviewmodel, ActivityShipingjianjiBinding>(R.layout.activity_shipingjianji),FabuAdapter.OnItemClickListener{
    var tupianlianjie=""
    private lateinit var bottomSheetDialog: BottomSheetDialog
    private lateinit var fabiada: FabuAdapter
    var list= mutableListOf<ZaoShuju>(
        ZaoShuju(2,""))
    var tupiansecailist= mutableListOf<String>()
    var listid=mutableListOf<Int>()
    var file: File?=null
    var tennum=0
    var tenwunum=0

    override fun onResume() {
        super.onResume()

        viewmodel.onwodezhuyewang(UserData.token,mapOf("id" to ""))

    }

    override fun initView() {
        binding.chongzhi.setOnClickListener {
            val inten=Intent(this, ShipingbaoActivity::class.java)
            startActivity(inten)
        }
        viewmodel.onwodezhuyewang(UserData.token,mapOf("id" to ""))

        binding.shengchengsp.setOnClickListener {



            if(binding.wengzisucai.text.length<=30){
                if(tennum==0){
                    Toast.makeText(this, "次数不够请充值", Toast.LENGTH_SHORT).show()
                }else
                {

                    binding.beijinghui.visibility= View.VISIBLE
                    binding.jiazaitu.visibility= View.VISIBLE
                    binding.jiazaiziti.visibility= View.VISIBLE
                    Glide.with(this).load(R.mipmap.jiazaitupian).into(binding.jiazaitu)
                    binding.jiazaiziti.text= "上传中 请稍等。。。"


                    val text=binding.wengzisucai.text.toString()
                    var listidstring=""
                    for ((inden ,i) in listid.withIndex()) {
                        if(inden==listid.size-1){
                            listidstring = listidstring+i
                        }else{
                            listidstring = listidstring+i+","
                        }
                    }
                    Log.e("图片id",listidstring)
                    var shuijian=""
                    if(binding.wengzisucai.text.length<=30){
                        shuijian="10"
                    }else{
                        shuijian="15"
                    }

                    viewmodel.onshengchengspwang(UserData.token,mapOf("text" to text,"mediaIds" to listid[0].toString(),"layout" to "1","ttsPer" to "4100","duration" to shuijian))



                }
            }else{

                if(tenwunum==0){
                    Toast.makeText(this, "次数不够请充值", Toast.LENGTH_SHORT).show()
                }else
                {

                    binding.beijinghui.visibility= View.VISIBLE
                    binding.jiazaitu.visibility= View.VISIBLE
                    binding.jiazaiziti.visibility= View.VISIBLE
                    Glide.with(this).load(R.mipmap.jiazaitupian).into(binding.jiazaitu)
                    binding.jiazaiziti.text= "上传中 请稍等。。。"


                    val text=binding.wengzisucai.text.toString()
                    var listidstring=""
                    for ((inden ,i) in listid.withIndex()) {
                        if(inden==listid.size-1){
                            listidstring = listidstring+i
                        }else{
                            listidstring = listidstring+i+","
                        }
                    }
                    Log.e("图片id",listidstring)
                    var shuijian=""
                    if(binding.wengzisucai.text.length<=30){
                        shuijian="10"
                    }else{
                        shuijian="15"
                    }

                    viewmodel.onshengchengspwang(UserData.token,mapOf("text" to text,"mediaIds" to listid[0].toString(),"layout" to "1","ttsPer" to "4100","duration" to shuijian))



                }
            }



        }
        binding.yingse.setOnClickListener {
            bottomSheetDialog = BottomSheetDialog(this)
            val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_yingse, null)
            bottomSheetDialog.setContentView(view)
            bottomSheetDialog.show()

        }


        binding.review.layoutManager=
            GridLayoutManager(this, 3)
        fabiada= FabuAdapter(this,list,this)
        binding.review.adapter= fabiada
    }

    override fun dataObservese() {

        viewmodel.onwodezhuye.observe(this, Observer {
            if(it.code==1){

                    binding.zhanshicishu.text="10sAI生成视频次数（${it.data.ten_seconds_num}） 15sAI生成视频次数（${it.data.fifteen_seconds_num}） 扣除1次AI生成视频次数"
                    tennum=it.data.ten_seconds_num
                    tenwunum=it.data.fifteen_seconds_num


                }

        })



        viewmodel.onshengchengsg.observe(this, Observer {
            if(it.code==1){
                if(it.data.data.detail[0].status==1){

                 val lianji=it.data.data.detail[0].url

                    binding.jiazaitu.visibility= View.GONE
                    binding.jiazaiziti.visibility= View.GONE
                    binding.beijinghui.visibility= View.GONE

                    val intent=Intent(this, ShipingbianjibofangActivity::class.java)
                    intent.putExtra("lianjie",lianji)
                    startActivity(intent)

                    Toast.makeText(this, "视频合成成功", Toast.LENGTH_SHORT).show()

                }else{


                    Handler(Looper.getMainLooper()).postDelayed({
                        viewmodel.onshengchengsgwang(UserData.token)
                    }, 5000) // 5000毫秒 = 5秒

                }


            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()

            }


        })


        //todo 第二部的操作
        viewmodel.onshengchengsp.observe(this, Observer {
            if(it.code==1){

                viewmodel.onshengchengsgwang(UserData.token)

                Log.e("第二部的的返回值","走到了")

            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()


            }



        })

        viewmodel.ontupiansucai.observe(this, Observer {
            if(it.code==1){
                if(it.data.code==0){
                    listid.add(it.data.data.mediaId)
                    binding.jiazaitu.visibility= View.GONE
                    binding.jiazaiziti.visibility= View.GONE
                    binding.beijinghui.visibility= View.GONE
                    Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show()

                    list.add(0,ZaoShuju(1,tupianlianjie))
                    Log.e("上传图片的半路径",tupianlianjie)

                    tupiansecailist.add(tupianlianjie)
                    binding.review.layoutManager=
                        GridLayoutManager(this, 3)
                    fabiada= FabuAdapter(this,list,this)
                    binding.review.adapter= fabiada



                }else{
                    binding.jiazaitu.visibility= View.GONE
                    binding.jiazaiziti.visibility= View.GONE
                    binding.beijinghui.visibility= View.GONE
                    Toast.makeText(this,"服务异常，请稍后重试", Toast.LENGTH_SHORT).show()


                }

            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()

            }



        })

        viewmodel.onlusc.observe(this, Observer {
            if(it.code==1){
                val params = mapOf("url" to "http://117ai.32.hzgqapp.com"+it.data.url)
                viewmodel.ontupiansucaiwang(UserData.token,params)

                tupianlianjie=it.data.url


            }


        })
    }

    override fun onItemClick(position: Int, uri: ZaoShuju) {
        if(uri.leixing==2){
            openGallery()

        }else{
            Toast.makeText(this, "图片预览中"+"    "+list.size, Toast.LENGTH_SHORT).show()


        }
    }


    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/* video/*"
        startActivityForResult(intent, GALLERY_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            data?.data?.let { uri ->
                file = File(getRealPathFromURI(uri))
                binding.beijinghui.visibility= View.VISIBLE
                binding.jiazaitu.visibility= View.VISIBLE
                binding.jiazaiziti.visibility= View.VISIBLE
                Glide.with(this).load(R.mipmap.jiazaitupian).into(binding.jiazaitu)
                binding.jiazaiziti.text= "上传中 请稍等。。。"
                val requestFile = file?.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                val body = MultipartBody.Part.createFormData("file", file?.name,requestFile!!)
                viewmodel.onluying(body)
            }
        }
    }

    private fun getRealPathFromURI(contentUri: Uri): String {
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = contentResolver.query(contentUri, projection, null, null, null)
        val column_index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor?.moveToFirst()
        val result = cursor?.getString(column_index!!)
        cursor?.close()
        return result!!
    }
    companion object {
        private const val GALLERY_REQUEST_CODE = 1001
    }

}